<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import { TravelNoteApi } from '@/api/new/travelNoteApi.js';
import { FollowRelationApi } from '@/api/FollowRelationApi.js';
import UserUtil from '@/utils/User/User.js';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';

// 用户信息
const userInfo = ref({});
const userStats = ref({
  following: 0,
  followers: 0,
  articles: 0  // 改为与个人页一致，显示文章数而非收藏数
});
const userTags = ref([]);
const isFollowing = ref(false);

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 获取当前登录用户ID
    const currentUserId = UserUtil.getUserId();
    
    // 获取要查看的用户ID（从路由参数）
    const targetUserId = route.query.userId;
    
    if (!targetUserId) {
      ElMessage.error('用户ID不存在');
      router.push('/dashboard');
      return;
    }
    
    // 获取用户信息
    const userData = await UserProfileApi.getUserInfo(targetUserId);
    userInfo.value = userData;
    
    // 设置用户标签（示例数据，实际应从API获取）
    userTags.value = ['程序员', '上海', '摄影爱好者'];
    
    // 获取用户统计数据
    try {
      // 获取关注数 - 使用 getFollowingCount API
      const followingResponse = await UserProfileApi.getFollowingCount(targetUserId);
      const followingData = typeof followingResponse === 'string' 
        ? JSON.parse(followingResponse) 
        : followingResponse;
      const followingCount = followingData?.followingCount || 0;
      
      // 获取粉丝数 - 使用 getFollowerCount API
      const followersResponse = await UserProfileApi.getFollowerCount(targetUserId);
      const followersData = typeof followersResponse === 'string' 
        ? JSON.parse(followersResponse) 
        : followersResponse;
      const followersCount = followersData?.followCount || 0;
      
      // 获取文章数 - 使用 getPublishedArticleCount API
      const articlesResponse = await UserProfileApi.getPublishedArticleCount(targetUserId);
      const articlesData = typeof articlesResponse === 'string' 
        ? JSON.parse(articlesResponse) 
        : articlesResponse;
      const articlesCount = articlesData?.publishedArticleCount || 0;
      
      userStats.value = {
        following: followingCount,
        followers: followersCount,
        articles: articlesCount
      };
    } catch (error) {
      console.error('获取用户统计数据失败:', error);
      // 使用默认值
    }
    
    // 检查是否已关注 - 使用 FollowRelationApi 替代 UserProfileApi
    if (currentUserId) {
      try {
        const followRelation = await FollowRelationApi.getFollowRelationByUserIds(
          currentUserId, 
          targetUserId
        );
        
        // 如果返回了关注关系对象（不是null），说明已关注
        isFollowing.value = followRelation !== null;
      } catch (error) {
        console.error('获取关注状态失败:', error);
        isFollowing.value = false;
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error(`获取用户信息失败: ${error.message || '未知错误'}`);
  }
};

// 关注/取消关注
const toggleFollow = async () => {
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    const currentUserId = UserUtil.getUserId();
    const targetUserId = userInfo.value.userID;
    
    if (isFollowing.value) {
      // 取消关注 - 使用 FollowRelationApi 替代 UserProfileApi
      await FollowRelationApi.deleteFollowRelation(currentUserId, targetUserId);
      isFollowing.value = false;
      ElMessage.success('已取消关注');
    } else {
      // 关注 - 使用 FollowRelationApi 替代 UserProfileApi
      const now = new Date().toISOString();
      await FollowRelationApi.createFollowRelation({
        followerID: currentUserId,
        followedID: targetUserId,
        createTime: now
      });
      isFollowing.value = true;
      ElMessage.success('关注成功');
    }
    
    // 刷新粉丝数
    const followersResponse = await UserProfileApi.getFollowerCount(targetUserId);
    const followersData = typeof followersResponse === 'string' 
      ? JSON.parse(followersResponse) 
      : followersResponse;
    userStats.value.followers = followersData?.followCount || 0;
  } catch (error) {
    console.error('关注操作失败:', error);
    ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
  }
};

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>

<template>
  <div class="user-page">
    <div class="user">
      <div class="user-info">
        <div class="avatar">
          <div class="avatar-wrapper">
            <img
              :src="userInfo.headshot || defaultAvatar"
              class="user-image"
              style="border: 1px solid rgba(0, 0, 0, 0.08)"
            />
          </div>
        </div>
        <div class="info-part">
          <div class="info">
            <div class="basic-info">
              <div class="user-basic">
                <div class="user-nickname">
                  <div class="user-name">{{ userInfo.username || '未知用户' }}</div>
                </div>
                <div class="user-content">
                  <span class="user-redId">账号：{{ userInfo.userID || '未知' }}</span>
                  <span class="user-IP"> IP属地：{{ userInfo.location || '未知' }}</span>
                </div>
              </div>
            </div>
            <div class="user-desc">
              {{ userInfo.bio || '这里没有简介' }}
            </div>
            <div class="user-tags">
              <div v-for="(tag, index) in userTags" :key="index" class="tag-item">
                <div>{{ tag }}</div>
              </div>
            </div>
            <div class="data-info">
              <div class="user-interactions">
                <div>
                  <span class="count">{{ userStats.following || 0 }}</span>
                  <span class="shows">关注</span>
                </div>
                <div>
                  <span class="count">{{ userStats.followers || 0 }}</span>
                  <span class="shows">粉丝</span>
                </div>
                <div>
                  <!-- 修改为显示文章数 -->
                  <span class="count">{{ userStats.articles || 0 }}</span>
                  <span class="shows">文章</span>
                </div>
              </div>
            </div>
          </div>
          <div class="follow">
            <el-button 
              :type="isFollowing ? 'default' : 'danger'" 
              size="large" 
              round
              @click="toggleFollow"
            >
              {{ isFollowing ? '已关注' : '关注' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="reds-sticky-box user-page-sticky" style="--1ee3a37c: all 0.4s cubic-bezier(0.2, 0, 0.25, 1) 0s">
      <div class="reds-sticky" style="">
        <div class="tertiary center reds-tabs-list" style="padding: 0px 12px">
          <div
              class="reds-tab-item active"
          >
            <span>笔记</span>
          </div>
          <!---->
          <div class="active-tag" style="width: 64px; left: 627px"></div>
        </div>
      </div>
    </div>
    <div class="feeds-tab-container" style="--1ee3a37c: all 0.4s cubic-bezier(0.2, 0, 0.25, 1) 0s">
      <router-view />
    </div>
  </div>
</template>

<style lang="less" scoped>
.user-page {
  background: #fff;
  overflow-y: scroll;
  overflow-x: hidden;

  .user {
    padding-top: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    .user-info {
      display: flex;
      justify-content: center;
      padding: 48px 0;

      .avatar {
        .avatar-wrapper {
          text-align: center;
          width: 250.66667px;
          height: 175.46667px;
          .user-image {
            border-radius: 50%;
            margin: 0 auto;
            width: 70%;
            height: 100%;
            object-fit: cover;
          }
        }
      }

      .info-part {
        position: relative;
        width: 100%;

        .info {
          @media screen and (min-width: 1728px) {
            width: 533.33333px;
          }
          margin-left: 32px;
          .basic-info {
            display: flex;
            align-items: center;
            .user-basic {
              width: 100%;
              .user-nickname {
                width: 100%;
                display: flex;
                align-items: center;
                max-width: calc(100% - 96px);
                .user-name {
                  font-weight: 600;
                  font-size: 24px;
                  line-height: 120%;
                  color: #333;
                }
              }
              .user-content {
                width: 100%;
                font-size: 12px;
                line-height: 120%;
                color: rgba(51, 51, 51, 0.6);
                display: flex;
                margin-top: 8px;
                .user-redId {
                  padding-right: 12px;
                }
              }
            }
          }
          .user-desc {
            width: 100%;
            font-size: 14px;
            line-height: 140%;
            color: #333;
            margin-top: 16px;
            white-space: pre-line;
          }
          .user-tags {
            height: 24px;
            margin-top: 16px;
            display: flex;
            align-items: center;
            font-size: 12px;
            color: #333;
            text-align: center;
            font-weight: 400;
            line-height: 120%;
            .tag-item :first-child {
              padding: 3px 6px;
            }
            .tag-item {
              display: flex;
              align-items: center;
              justify-content: center;
              padding: 4px 8px;
              grid-gap: 4px;
              gap: 4px;
              height: 18px;
              border-radius: 41px;
              background: rgba(0, 0, 0, 0.03);
              height: 24px;
              margin-right: 8px;
              color: rgba(51, 51, 51, 0.6);
            }
          }
          .data-info {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 20px;
            .user-interactions {
              width: 100%;
              display: flex;
              align-items: center;
              .count {
                font-weight: 500;
                font-size: 14px;
                margin-right: 4px;
              }
              .shows {
                color: rgba(51, 51, 51, 0.6);
                font-size: 14px;
                line-height: 120%;
              }
            }
            .user-interactions > div {
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              text-align: center;
              margin-right: 16px;
            }
          }
        }

        .follow {
          position: absolute;
          margin-left: auto;
          display: block;
          right: 0;
          top: 0;
        }
      }
    }
  }

  .reds-sticky {
    padding: 16px 0;
    z-index: 5 !important;
    background: hsla(0, 0%, 100%, 0.98);
    user-select: none;

    .reds-tabs-list {
      screen and (min-width: 1728px) {
        width: 1445.33333px;
      }
      display: flex;
      flex-wrap: nowrap;
      position: relative;
      font-size: 16px;
      justify-content: center;

      .reds-tab-item {
        padding: 0px 16px;
        margin-right: 0px;
        font-size: 16px;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        height: 40px;
        cursor: pointer;

        color: rgba(51, 51, 51, 0.8);
        white-space: nowrap;
        transition: transform 0.3s cubic-bezier(0.2, 0, 0.25, 1);
        z-index: 1;
      }
      .reds-tab-item.active {
        background-color: rgba(0, 0, 0, 0.03);
        border-radius: 20px;
        font-weight: 600;
        color: rgba(51, 51, 51, 0.8);
      }
    }
  }

  .feeds-tab-container {
    padding-left: 2rem;
  }
}
</style>